package com.common.util;

import com.common.constant.ApplicationConstant;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hzyzt.user.dto.UserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;


/**
 * Class Name: WebUtil Description: TODO.
 * 
 * @author SC
 * 
 */
public final class WebUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebUtil.class);

    private static ObjectMapper objectMapper;

    private static final int NUMBER100 = 100;
    
    private WebUtil() {

    }

    /**
     * Description: get the current request bound to current thread.
     *
     * @return
     */
    public static HttpServletRequest getThreadRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * Description:.
     *
     * @return
     */
    public static HttpSession getThreadSession() {
        return getThreadRequest().getSession(true);
    }

    /** 
     * @Title: getSessionUser 
     * @Description: 
     * @Auth wentaolu
     * @Date Jul 22, 2016 3:23:22 PM
     * @return
     * @throws 
     */
    public static UserDto getSessionUser() {
        HttpSession session = getThreadRequest().getSession(true);
        UserDto userDto = (UserDto) session.getAttribute(ApplicationConstant.SESSIONUSER);
        return userDto;
    }

    public static String getSessionUserName() {

        return getSessionUser().getUserName();
    }

    public static String getSessionUserId() {
        String userId = Long.toString(getSessionUser().getUserId());
        return userId;
    }

    /**
     * Description: determine whether current request is sent via AJAX.
     *
     * @return
     */
    public static boolean isAjaxRequest() {
        return isAjaxRequest(getThreadRequest());
    }

    /**
     * Description: determine whether given request is sent via AJAX.
     *
     * @param request
     * @return
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("X-Requested-With");
        return requestedWith != null ? "XMLHttpRequest".equals(requestedWith) : false;
    }

    /**
     * Description: get the full URL for a relative path.
     *
     * @param path
     * @return
     */
    public static String getFullUrlBasedOn(String path) {
        StringBuilder targetUrl = new StringBuilder();
        if (path.startsWith("/")) {
            // Do not apply context path to relative URLs.
            targetUrl.append(getThreadRequest().getContextPath());
        }
        targetUrl.append(path);
        return targetUrl.toString();
    }

    /**
     * Description: get the full URL for a relative path.
     *
     * @return
     */
    public static String getContextPath() {
        StringBuilder targetUrl = new StringBuilder();
        // Do not apply context path to relative URLs.
        targetUrl.append(getThreadRequest().getContextPath());
        return targetUrl.toString();
    }

    /**
     * @Title: getSessionId 
     * @Description: 
     * @Auth wentaolu
     * @Date Jul 22, 2016 3:24:43 PM
     * @return
     * @throws 
     */
    public static String getSessionId() {
        HttpSession session = getThreadSession();
        if (null == session) {
            return null;
        }
        return session.getId().toString();
    }

    /** 
     * @Title: getServletContext 
     * @Description: 
     * @Auth wentaolu
     * @Date Jul 22, 2016 3:24:48 PM
     * @return
     * @throws 
     */
    public static ServletContext getServletContext() {
        HttpSession session = getThreadSession();
        if (null == session) {
            return null;
        }
        return session.getServletContext();
    }

    /**
     * Description: 获取客户端ip.
     *
     * @return
     */
    public static String getRemoteAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * Description: 通过命令nbtstat -a ip来获得该ip相对应的mac地址.
     * 
     * @return String MAC地址
     */
    public static String getMACAddress(String ip) {
        String str = "";
        String macAddress = "";
        try {
            Process p = Runtime.getRuntime().exec("nbtstat -a " + ip);
            InputStreamReader ir = new InputStreamReader(p.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (int i = 1; i < NUMBER100; i++) {
                str = input.readLine();
                if (str != null && str.indexOf("MAC") > 1) {
                    macAddress = str.substring(str.indexOf('=') + 2, str.length());
                    break;
                }
            }
            ir.close();
            input.close();
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        
        return macAddress;
    }
    
    /** 
     * @Title: setResponseHeader 
     * @Description: 设置头信息.
     * @Auth shuxinwu
     * @Date 2016年11月15日 下午5:40:42
     * @throws
     */
    public static void setResponseHeader(Object[] objects){
    	HttpServletResponse response = null;
    	Boolean ifHtml5 = null;
    	for(Object o:objects){
    		if(o instanceof HttpServletResponse){
    			response = (HttpServletResponse) o;
    		}
    		if(o instanceof Boolean){
    			ifHtml5 = (Boolean) o;
    		}
    	}
    	try {
    		if(ifHtml5){
    			response.setContentType("text/html;charset=UTF-8");
    		}else{
    			response.setContentType("application/json;charset=UTF-8");
    		}
		} catch (Exception e) {
			LOGGER.error(StackTraceUtil.getStackTrace(e));
		}
		
    }
    
    /**
     * 从请求头中获取请求来源，判断是Android还是iPhone还是Web.
     * 
     * （该判断为粗略统计：Opera mobile(android)、Opera mini(iphone)、
     * android平台ucweb急速模式关闭状态下的http_user_agent、UC浏览器（Android）、QQ HD浏览器（iPhone）  等等一些特殊请求头不做区分）
     * @return
     */
    public static String getRequestOrigin(){
        String agent = getThreadRequest().getHeader("user-agent");
        if(agent.indexOf("iPhone")>=0){
            return "iPhone";
        }else if(agent.indexOf("Android")>=0 || agent.indexOf("User-Agent")>=0){
            return "Android";
        }else{
            return "Web";
        }
    }
    
    public static boolean isRightUser(String userId){
    	String type = WebUtil.getRequestOrigin();
    	boolean flag = false;//账户是否有问题
    	if (type.indexOf("Android")>=0) {
    		 String agent = getThreadRequest().getHeader("user-agent");
    		 if(agent.indexOf("User-Agent")>=0){
    	    		return flag;
    	    	}
    	    	if(agent.indexOf("Android")>=0 ){
    	    		String[] str = agent.split("&");
    	    		if (str.length == 2) {
    					String[] str1 = str[1].split("=");
    					if(!userId.equals(str1[1])){
    						flag = true;
    					}
    				}else {
    					flag = true;
    				}
    	    		return flag;
    	    	}
		}
    	
    	
    	if("Web".equals(type)){
    		flag = true;
    	}else{
    		if(!"".equals(userId)){
                UserDto user = WebUtil.getSessionUser();
    			
        		if(StringUtil.isObjNull(user)){//没登录信息
        			flag = true;
        		}else{
        			if(!userId.equals(user.getUserId()+"")){//不是同一个人
        				flag = true;
        			}
        		}
    		}
    		
    	}
    	return flag;
    }
    

}
